package net.sending;

import util.Config;

import java.net.*;
import java.io.IOException;

public class SocketFactory {

    public static final InetAddress BROADCAST_HOST = createHost();

    private static DatagramSocket broadcastSocket = null;

    public static Socket getSocket(InetAddress ip) {
        Socket socket = null;
        try {
            socket = new Socket(ip, Config.getInstance().getReceivePort());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return socket;
    }

    public static DatagramSocket getBroadcastSocket() {
        if (broadcastSocket == null) {
            try {
                broadcastSocket = new DatagramSocket(Config.getInstance().getSendPort());
                broadcastSocket.setBroadcast(true);
            } catch (SocketException e) {
                e.printStackTrace();
            }
        }
        return broadcastSocket;
    }

    private static InetAddress createHost() {
        InetAddress res = null;
        try {
            res = InetAddress.getByName("255.255.255.255");
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return res;
    }
}
